<?php
class analysisModel extends RPHP_Model
{

    protected $_auth = null;
    public $datap = [];
    //检查权限
    public function checkPriv($pv, $return = true, $menu = true)
    {
        $auth = $this->auth->CheckPriv($pv, $return, $menu);
        if ($return) {
            $this->_auth = $auth;
        }

        return $auth;
    }

    //获取该邀请码下的所有用户
    public function getRecodeMember($recode,$items=[])
    {
        $uid = $this->table('member_account')->findOneBySql("`recode`='".$recode."'","uid");

        if ( $uid ) {

            $data = $this->table('member_account')->findAllBySql("`pid`=".$uid,"uid,recode,member_level,maker_level");
            if ( !$data ) {
                $items = [];
            }

            if ($data) {
                foreach ($data as $key => $value) {
                    $tmp = $this->table('member_account')->findAllBySql("`pid`=".$value['uid'],"uid,recode,member_level,maker_level");
                    
                    $items = array_merge($items,$data);

                    if ( count($tmp) > 0 ) {

                        $items = $this->getRecodeMember($value['recode'],$items);
                        
                    }
                }
            }
        }
        $items = array_unique($items, SORT_REGULAR);
        return $items;
    }

    //获取该邀请码下的所有用户ID
    public function getRecodeMemberID($recode,$items="")
    {
        $uid = $this->table('member_account')->findOneBySql("`recode`='".$recode."'","uid");

        if ( $uid ) {

            $data = $this->table('member_account')->findAllBySql("`pid`=".$uid,"uid,recode,member_level,maker_level");
            if ( !$data ) {
                $items = "";
            }

            if ($data) {
                foreach ($data as $key => $value) {
                    $tmp = $this->table('member_account')->findOneBySql("`pid`=".$value['uid'],"uid");
                    
                    $items .= $value['uid'].',';

                    if ( $tmp ) {

                        $items = $this->getRecodeMemberID($value['recode'],$items);
                        
                    }
                }
            }
        }
        // $items = array_unique($items, SORT_REGULAR);
        return $items;
    }

    //新增重销统计
    public function getMoreSell($para)
    {

        if ($para['keyword'] != '') {
            $uid = $this->table('member_account')->findOneBySql("`recode` = '".$para['keyword']."'",'uid');

        }
        $data = [];

        if($uid){
            $goods_ids = "";
            if ($para['caids'] != '') {

                //获取二级分类
                $goods_id_arr = $this->getScate(implode(',',$para['caids']));
               if($goods_id_arr){
                   $goods = $this->table("goods_data")->findAllBySql("`caid` IN (".implode(',',$goods_id_arr).")","`goods_id`");
                   if($goods){
                       $goods_idss =  array_unique(array_column($goods,'goods_id'));
                       $goods_ids  = implode(',',$goods_idss);
                   }
               }



            }

            $members =  $this->getAllMemberList($para['start_time'],$para['end_time']);
            $order = $this->getAllOrder(implode(',',$members['user_ids']),$goods_ids,$para['start_time'],$para['end_time']);
            $members =  $this->getAllMemberList($para['start_time'],$para['end_time']);
            if($order){

                if($members['child'][$uid]){
                    //自购
                    $data['my_money'] = $order[$uid] ?: 0;
                    //会员等级业绩
                    $data['member_level0_money'] =  $data['member_level1_money'] =  $data['member_level2_money'] = $data['member_level3_money'] = 0;

                    //创客等级业绩
                    $data['maker_level1_money'] =  $data['maker_level2_money'] =  $data['maker_level3_money'] = $data['maker_level4_money'] =$data['maker_level5_money']= 0;
                    //团队业绩
                    $data['team_money'] = 0;
                    //团队365及以上会员消费业绩
                    $data['member_level_money'] = 0;



                    // dd($members['child'][452]);
                    foreach ($members['child'][$uid] as $r) {

                        $data['team_money'] += $order[$r['uid']] ?: 0;

                        if($r)

                        $done = false;
                        switch ($r['maker_level']){


                            case 1:
                                $data['maker_level1_money']  +=$order[$r['uid']] ?: 0;
                                $done = true;
                                break;
                            case 2:
                                $data['maker_level2_money']  +=$order[$r['uid']] ?: 0;
                                $done = true;
                                break;
                            case 3:
                                $data['maker_level3_money']  +=$order[$r['uid']] ?: 0 ;
                                $done = true;
                                break;
                            case 4:
                                $data['maker_level4_money']  +=$order[$r['uid']] ?: 0 ;
                                $done = true;
                                break;
                            case 5:
                                $data['maker_level5_money']  +=$order[$r['uid']] ?: 0;
                                $done = true;
                                break;
                        }
                        if(!$done){
                            switch ($r['member_level']){

                                case 0:
                                    $data['member_level0_money']  +=$order[$r['uid']] ?: 0 ;
                                    break;
                                case 1:
                                    $data['member_level1_money']  +=$order[$r['uid']] ?: 0;
                                    break;
                                case 2:
                                    $data['member_level2_money']  +=$order[$r['uid']] ?: 0 ;
                                    break;
                                case 3:
                                    $data['member_level3_money']  +=$order[$r['uid']] ?: 0 ;
                                    break;
                            }


                        }
                        $this->datap = [];
                        $child = $this->findAllChild($members['child'], $r['uid']);

                        $child = $this->datap;
                        //$data['user'][] = $child['users'];
                        if ($child['users']) {
                            $data['team_num'] +=count($child['uid']);

                            foreach ($child['users'] as $cuid) {

                                $data['team_money'] += $order[$cuid['uid']] ?: 0;


                                $done = false;
                                switch ($cuid['maker_level']){


                                    case 1:
                                        $data['maker_level1_money']  +=$order[$cuid['uid']] ?: 0;
                                        $done = true;
                                        break;
                                    case 2:
                                        $data['maker_level2_money']  +=$order[$cuid['uid']] ?: 0 ;
                                        $done = true;
                                        break;
                                    case 3:
                                        $data['maker_level3_money']  +=$order[$cuid['uid']] ?: 0 ;
                                        $done = true;
                                        break;
                                    case 4:
                                        $data['maker_level4_money']  +=$order[$cuid['uid']] ?: 0 ;
                                        $done = true;
                                        break;
                                    case 5:
                                        $data['maker_level5_money']  +=$order[$cuid['uid']] ?: 0 ;
                                        $done = true;
                                        break;
                                }
                                if(!$done){
                                    switch ($cuid['member_level']){

                                        case 0:
                                            $data['member_level0_money']  +=$order[$cuid['uid']] ?: 0 ;
                                            break;
                                        case 1:
                                            $data['member_level1_money']  +=$order[$cuid['uid']] ?: 0 ;
                                            break;
                                        case 2:
                                            $data['member_level2_money']  +=$order[$cuid['uid']] ?: 0 ;
                                            break;
                                        case 3:
                                            $data['member_level3_money']  +=$order[$cuid['uid']] ?: 0 ;
                                            break;
                                    }


                                }

                            }
                        }
                    }

                    $data['member_level_money']  = fun_price($data['member_level1_money'] + $data['member_level2_money'] + $data['member_level3_money']);

                }
            }

        }

        return $data;

    }


    //获取用户统计
    public function getMemberTotal($para)
    {
        $uid = 0;
        if ($para['keyword'] != '') {
            $uid = $this->table('member_account')->findOneBySql("`recode` = '".$para['keyword']."'",'uid');

        }
        $data = [];
        if($uid){
//$para['start_time'],$para['end_time']
            $members =  $this->getAllMemberList();

            $order = $this->getAllOrder(implode(',',$members['user_ids']));
           // if($order){

                 if($members['child'][$uid]){
                    //dd($members['child'][$uid]);
                     //团队数量
                     $data['team_num'] = 1;

                    // $data['team_num'] +=count($members['child'][$uid]);
                     //直推人数
                     $data['zt_num'] =0;
                     //会员等级数量
                     $data['member_level0_num'] =  $data['member_level1_num'] =  $data['member_level2_num'] = $data['member_level3_num'] = 0;

                     //创客等级数量
                     $data['maker_level1_num'] =  $data['maker_level2_num'] =  $data['maker_level3_num'] = $data['maker_level4_num'] =$data['maker_level5_num']= 0;
                     //团队业绩
                     $data['team_money'] = 0;
                     //团队365及以上会员消费业绩
                     $data['member_level_money'] = 0;
                     //团队西客会员消费业绩
                     $data['member_level0_money'] = 0;


                        // dd($members['child'][452]);
                     foreach ($members['child'][$uid] as $r) {
                         $d_time =true;
                         if($para['start_time']>0){

                             if($r['create_time']<$para['start_time']){
                                 $d_time = false;

                             }

                         }

                         if($para['end_time']>0){

                             if($r['create_time']>$para['end_time']){
                                 $d_time = false;

                             }

                         }

                         if($d_time){

                             $data['team_num']  +=1;
                             $data['zt_num'] +=1;


                             $data['team_money'] += $order[$r['uid']] ?: 0;

                             if($r['member_level']>0){
                                 $data['member_level_money'] +=$order[$r['uid']] ?: 0;
                             }

                             if($r['member_level']==0){

                                 $data['member_level0_money'] +=$order[$r['uid']] ?: 0;
                             }


                             $done = false;
                             switch ($r['maker_level']){


                                 case 1:
                                     $data['maker_level1_num']  +=1 ;
                                     $done = true;
                                     break;
                                 case 2:
                                     $data['maker_level2_num']  +=1 ;
                                     $done = true;
                                     break;
                                 case 3:
                                     $data['maker_level3_num']  +=1 ;
                                     $done = true;
                                     break;
                                 case 4:
                                     $data['maker_level4_num']  +=1 ;
                                     $done = true;
                                     break;
                                 case 5:
                                     $data['maker_level5_num']  +=1 ;
                                     $done = true;
                                     break;
                             }
                             if(!$done){
                                 switch ($r['member_level']){

                                     case 0:
                                         $data['member_level0_num']  +=1 ;
                                         break;
                                     case 1:
                                         $data['member_level1_num']  +=1 ;
                                         break;
                                     case 2:
                                         $data['member_level2_num']  +=1 ;
                                         break;
                                     case 3:
                                         $data['member_level3_num']  +=1 ;
                                         break;
                                 }


                             }
                             $this->datap = [];
                             $child = $this->findAllChild($members['child'], $r['uid']);

                             $child = $this->datap;

                             //$data['user'][] = $child['users'];
                             if ($child['users']) {
                                 //$data['team_num'] +=count($child['uid']);

                                 foreach ($child['users'] as $cuid) {

                                     $d_time =true;
                                     if($para['start_time']>0){

                                         if($r['create_time']<$para['start_time']){
                                             $d_time = false;

                                         }

                                     }

                                     if($para['end_time']>0){

                                         if($r['create_time']>$para['end_time']){
                                             $d_time = false;

                                         }

                                     }

                                     if($d_time){

                                         $data['team_num'];

                                         $data['team_money'] += $order[$cuid['uid']] ?: 0;

                                         if($cuid['member_level']>0){
                                             $data['member_level_money'] +=$order[$cuid['uid']] ?: 0;
                                         }

                                         if($cuid['member_level']==0){

                                             $data['member_level0_money'] +=$order[$cuid['uid']] ?: 0;
                                         }

                                         $done = false;
                                         switch ($cuid['maker_level']){


                                             case 1:
                                                 $data['maker_level1_num']  +=1 ;
                                                 $done = true;
                                                 break;
                                             case 2:
                                                 $data['maker_level2_num']  +=1 ;
                                                 $done = true;
                                                 break;
                                             case 3:
                                                 $data['maker_level3_num']  +=1 ;
                                                 $done = true;
                                                 break;
                                             case 4:
                                                 $data['maker_level4_num']  +=1 ;
                                                 $done = true;
                                                 break;
                                             case 5:
                                                 $data['maker_level5_num']  +=1 ;
                                                 $done = true;
                                                 break;
                                         }
                                         if(!$done){
                                             switch ($cuid['member_level']){

                                                 case 0:
                                                     $data['member_level0_num']  +=1 ;
                                                     break;
                                                 case 1:
                                                     $data['member_level1_num']  +=1 ;
                                                     break;
                                                 case 2:
                                                     $data['member_level2_num']  +=1 ;
                                                     break;
                                                 case 3:
                                                     $data['member_level3_num']  +=1 ;
                                                     break;
                                             }


                                         }
                                     }

                                 }
                             }
                         }

                     }

                 }
            //}

        }

        return $data;
    }

    //获取团队时间段所有用户
  public $user_ids = [];
    public function getMemeberAll($uid = 0,$start_time=0,$end_time=0,$d=[])
    {
        if($start_time){

            $where = " AND `create_time` >".$start_time;
        }

        if($end_time){

            $where = " AND `create_time` <".$end_time;
        }
        $tmp = $this->table('member_account')->findAllBySql("`stat`=1 AND `pid`=".$uid.$where, "`uid`");
        if($tmp){
            foreach($tmp as $r){
                $this->user_ids[] = $r['uid'];
                   if($r['uid']){
                        $this->getMemeberAll($r['uid'],$start_time, $end_time);
                   }

            }


        }

       // return $d;

    }

    // 获取r
    public function getAllMemberList($start_time="",$end_time="")
    {
        $where = "";
        if($start_time){

            $where .= " AND `create_time` >".$start_time;
        }

        if($end_time){

            $where .= " AND `create_time` <".$end_time;
        }

        $tmp = $this->table('member_account')->findAllBySql("`stat`=1 ".$where, "`uid`,`pid`,`member_level`,`maker_level`,`recode`,`realname`,`name`,`mobile`,`create_time`");
        if ($tmp) {

            foreach ($tmp as $r) {
                $user_ids[] = $r['uid'];
                $members[$r['uid']] = $r;
                if ($r['pid'] > 0) {

                    $child[$r['pid']][] = $r;
                }

            }

        }
        return array(
            'user_ids'=>$user_ids,
            'child'=>$child,
            'members'=>$members,
        );

    }



    public function findAllChild($child, $uid = 0)
    {
        if ($child[$uid]) {
            foreach ($child[$uid] as $r) {

                $this->datap['uid'][] = $r['uid'];
                $this->datap['users'][] = $r;
                if ($child[$r['uid']]) {
                    $this->findAllChild($child, $r['uid']);
                }
            }
        }

    }

    //所属商品订单信息
    public function getAllOrder($uids = "",$goods_ids="",$start_time=0,$end_time=0)
    {
        $where = "";
        if($goods_ids){
            $where .= " AND  g.`goods_id` IN (".$goods_ids.")";

        }

        if($start_time){

            $where .= " AND o.`add_time` >".$start_time;
        }

        if($end_time){

            $where .= " AND o.`add_time` <".$end_time;
        }

        if($uids){
            $where .= " AND  o.`uid` IN (".$uids.")";
        }

       

        $sql = "SELECT o.`uid`,g.`goods_price` * g.`goods_number` AS `money`  FROM {$this->_prefix['primary']}order_info AS o LEFT JOIN {$this->_prefix['primary']}order_goods AS g ON o.`order_id`= g.`order_id`  WHERE   o.`pay_status`>0 ".$where;

        $rs = $this->sql($sql);
        $data = [];
        if ($rs) {
            foreach ($rs as $r) {
                $data[$r['uid']] += $r['money'];
            }
        }

        return $data;
    }

    //获取用户足迹
    public function getMemberFootMark($para, $page = 1, $pagesize = 1000)
    {
        $where = " 1=1 ";
        if ($para['keyword'] != '') {
            $uid = $this->table('member_account')->findOneBySql("`recode` = '".$para['keyword']."'",'uid');

        }

        if($para['start_time']){

            $where .= " AND `create_time` >".$para['start_time'];
        }

        if($para['end_time']){

            $where .= " AND `create_time` <".$para['end_time'];
        }

        //dd($para);

       if($uid){
           $members =  $this->getAllMemberList($para['start_time'],$para['end_time']);


           $this->datap['uid'][] = $uid;
           if(!in_array($uid,$members['user_ids'])){


                $u = $this->table("member_account")->findBySql("`uid`=".$uid, "`uid`,`pid`,`member_level`,`maker_level`,`recode`,`realname`,`name`,`mobile`,`create_time`");

                $members['members'][$u['uid']] = $u;
           }
           if($members['child'][$uid] ){
               $users_ids = [];
               $users = [];
               foreach($members['child'][$uid] AS $r){

                   $this->datap['uid'][] = $r['uid'];
                   $child = $this->findAllChild($members['child'], $r['uid']);

               }

               $users_ids = $this->datap['uid'];

           }

           $where.= " AND `uid` IN (".implode(',',$users_ids).") ";

           $sql = "SELECT COUNT(*) AS `cnt` FROM {$this->_prefix['primary']}goods_history WHERE " . $where;
           $cnt = $this->db->getone($sql);
          // echo $where;
           if ($cnt > 0) {



               $start = ($page - 1) * $pagesize;
               //默认排序
               $orderby = " `id` DESC";

               $sql = "SELECT * FROM {$this->_prefix['primary']}goods_history WHERE " . $where . " ORDER BY " . $orderby . " LIMIT " . $start . "," . $pagesize;
               $rs  = $this->sql($sql);
               $goods_ids = array_unique(array_column($rs,'goods_id'));

               $goods = $this->table("goods_data")->findAllBySql("`goods_id` IN (".implode(',',$goods_ids).")","`goods_id`,`goods_name`");

               if($goods){
                   foreach($goods as $key=>$val){
                       $goods_data[$val['goods_id']] = $val['goods_name'];

                   }

               }

           }

       }


//dd($members['members']);
        return array(
            'page'    => $page,
            'maxpage' => ceil($cnt / $pagesize),
            'count'   => $cnt,
            'data'    => $rs,
            'para'    => $para,
            'members'    => $members['members'],
            'goods'    => $goods_data,
        );

    }

    //获取用户门店
    public function getMyStore()
    {
        $sql = "SELECT `uid` FROM {$this->_prefix['primary']}shop_store WHERE `staffid`=" . $this->_auth['staffid'] . " AND `stat`=1 ORDER BY `storeid` DESC LIMIT 1";
        $uid = $this->db->getone($sql);
        return $uid;
    }

    //获取名店
    public function getstore()
    {
        $sql = "SELECT storeid,name FROM {$this->_prefix['primary']}shop_store";
        $res = $this->sql($sql);
        return $res;
    }
    //获取单个门店的名称
    public function getstorename($id)
    {
        $sql = "SELECT name FROM {$this->_prefix['primary']}shop_store WHERE storeid=" . $id;
        $res = $this->sql($sql);
        return $res;
    }

    //获取首页图表数据
    public function getHomeChartData($start_time = 0, $end_time = 0)
    {
        $where = " AND 1=1 ";

        if ($start_time > 0) {
            $date_time = $start_time;
            if ($end_time > 0) {
                $date_end_time = $end_time;
                $where .= " AND `add_time` >= " . $start_time . " AND `add_time` < " . $end_time;

            } else {
                $date_end_time = $_SERVER['REQUEST_TIME'];
                $where .= " AND `add_time` >= " . $start_time;

            }
        } else {
            //默认开始时间为当前时间的本年1月1号$_SERVER['REQUEST_TIME']
            $y         = date("Y", $_SERVER['REQUEST_TIME']) - 1;
            $m         = date("m", $_SERVER['REQUEST_TIME']);
            $date_time = $time_start = strtotime(date($y . "-" . $m . "-1 0:0:0"));
            if ($end_time > 0) {
                $date_end_time = $end_time;
                $where .= " AND `add_time` >= " . $time_start . " AND `add_time` < " . $end_time;

            } else {
                $date_end_time = $time_end = $_SERVER['REQUEST_TIME'];
                $where .= " AND `add_time` >= " . $time_start . " AND `add_time` < " . $time_end;
            }
        }
        /*
        订单数据
         */

        $order['count'] = 0;
        //已付款订单
        $sql  = "SELECT `goods_amount`,`order_id`,`add_time` FROM {$this->_prefix['primary']}order_info WHERE   `pay_status`=2" . $where;
        $data = $this->sql($sql);
        if ($data) {
            $order['count'] += count($data);
            foreach ($data as $r) {
                $m = date("Y-m", $r['add_time']);
                $order['payed']['count'][$m] += 1;
                $order['payed']['money'][$m] += $r['goods_amount'];
            }

        }
        //未付款订单
        $sql  = "SELECT `goods_amount`,`order_id`,`add_time` FROM {$this->_prefix['primary']}order_info WHERE  `pay_status`=0" . $where;
        $data = $this->sql($sql);
        if ($data) {
            $order['count'] += count($data);
            foreach ($data as $r) {
                $m = date("Y-m", $r['add_time']);
                $order['unpay']['count'][$m] += 1;
                $order['unpay']['money'][$m] += $r['goods_amount'];
            }
        }

        $eofmon     = (date("Y", $date_end_time) - date("Y", $date_time)) * 12 + (date("m", $date_end_time) - date("m", $date_time));
        $start      = (date("n", $date_time) - 1);
        $year_start = date("Y", $date_time);
        for ($i = 0; $i <= $eofmon; $i++) {

            $start = $start + 1;
            if ($start > 12) {
                $year_start = $year_start + 1;
                $start      = 1;
            }
            if ($start < 10) {
                $date[$i] = $year_start . "-0" . $start;
            } else {
                $date[$i] = $year_start . "-" . $start;
            }
        }

        foreach ($date as $k => $v) {
            $order['payed']['count'][$v] = $order['payed']['count'][$v] != "" ? $order['payed']['count'][$v] : 0;
            $order['payed']['money'][$v] = $order['payed']['money'][$v] != "" ? $order['payed']['money'][$v] : 0;
            $order['unpay']['count'][$v] = $order['unpay']['count'][$v] != "" ? $order['unpay']['count'][$v] : 0;
            $order['unpay']['money'][$v] = $order['unpay']['money'][$v] != "" ? $order['unpay']['money'][$v] : 0;
            $order['total']['count'][$v] = $order['payed']['count'][$v] + $order['unpay']['count'][$v];
            $order['total']['money'][$v] = $order['payed']['money'][$v] + $order['unpay']['money'][$v];
        }

        if ($order['total']['count']) {
            for ($i = 0; $i <= $eofmon; $i++) {
                if ($order['total']['count'][$date[$i - 1]] > 0) {
                    $order['total']['ratescount'][$date[$i]] = ($order['total']['count'][$date[$i]] - $order['total']['count'][$date[$i - 1]]) / $order['total']['count'][$date[$i - 1]] * 100;
                }
                if ($order['total']['count'][$date[$i - 1]] <= 0) {
                    $order['total']['ratescount'][$date[$i]] = ($order['total']['count'][$date[$i]] - 0) / 1 * 100;
                }
            }
        }
        if ($order['total']['money']) {
            for ($i = 0; $i <= $eofmon; $i++) {
                if ($order['total']['money'][$date[$i - 1]] > 0) {
                    $order['total']['ratesmoney'][$date[$i]] = ($order['total']['money'][$date[$i]] - $order['total']['money'][$date[$i - 1]]) / $order['total']['money'][$date[$i - 1]] * 100;
                }
                if ($order['total']['money'][$date[$i - 1]] <= 0) {
                    $order['total']['ratesmoney'][$date[$i]] = ($order['total']['money'][$date[$i]] - 0) / 1 * 100;
                }
            }
        }
        $start_year = date("Y", $date_time);
        $end_year   = date("Y", $date_end_time);
        if ($start_year == $end_year) {
            $year = $start_year;
        } else {
            $year = $start_year . "~" . $end_year;
        }

        return array(
            'date'      => $year,
            'start'     => date("Y-m月", $date_time),
            'end'       => date("Y-m月", $date_end_time),
            'eofmon'    => date("n", $date_end_time),
            'order'     => $order,
            'date_time' => $date,
        );
    }

    //获取所有类别
    public function getCategory($caid = 0, $isfucaid = false)
    {
        if ($isfucaid) {
            $tsql = " AND `fucaid`=" . intval($caid);
        } elseif ($caid > 0) {
            $tsql = " AND `caid`=" . intval($caid);
        }

        $sql = "SELECT * FROM {$this->_prefix['primary']}goods_category WHERE  `stat`=1" . $tsql . " ORDER BY `fucaid` ASC,`sort` ASC,`stat` ASC,`caid` ASC";

        if ($caid > 0 && !$isfucaid) {
            $newdata = $this->db->getrow($sql);
        } else {
            $data = $this->sql($sql);
            if ($data) {
                if ($isfucaid) {
                    $newdata = $data;
                } else {
                    foreach ($data as $r) {
                        $newdata[$r['fucaid']][$r['caid']] = $r;
                    }
                }
            }
        }
        return $newdata;
    }

    //获取商品分类父类
    public function getPcate()
    {
        return $this->table('goods_category')->findAllBySql("`stat`<3 AND fucaid=0");

    }

    // 获取指定下属类别
    public function getScate($fucaid = "")
    {
        $sql  = "SELECT `caid` FROM {$this->_prefix['primary']}goods_category WHERE `fucaid` IN (".$fucaid.")";
        $data = $this->sql($sql);
        if ($data) {
            foreach ($data as $r) {
                $new[] = $r['caid'];
            }
            return $new;
        }
        return false;
    }


    // 获取指定下属类别
    public function getSmlCate($fucaid = 0)
    {
        $sql  = "SELECT `caid` FROM {$this->_prefix['primary']}goods_category WHERE `fucaid`=" . intval($fucaid) . " AND `stat`<3";
        $data = $this->sql($sql);
        if ($data) {
            foreach ($data as $r) {
                $new[] = $r['caid'];
            }
            return $new;
        }
        return false;
    }

    public function getStaticList($para)
    {
        $where = " statu = 1 ";
        $wh = "  ";
        if ($para['keyword'] != '') {
            if(is_numeric($para['keyword'])){
                $where .= "   AND  `id` = ".$para['keyword'];
            }else{
                $where .= "   AND `supplier` LIKE '%" . $para['keyword'] . "%'";
            }

        }

        if ($para['goods_id'] != '') {
            $wh .= "   AND ogd.`goods_id` = ".$para['goods_id'];
        }

        if ($para['start_time'] > 0) {
            $wh .= " AND ord.`add_time`>=" . $para['start_time'];
        }

        if ($para['end_time'] > 0) {
            $wh .= " AND ord.`add_time`<=" . $para['end_time'];
        }
        $arr = [];
        $suppliers = $this->table("supplier")->findAllBySql($where,"id,supplier");
        $supp_ids =  array_column($suppliers, 'id');

        if($supp_ids){

            $wh .=" AND ogd.`supplierid` IN (".implode(',',$supp_ids).") AND ord.pay_status>0";
            $sql = "SELECT ord.`uid`,ord.`coupon_fee`,ord.`ximi_fee`,ord.`order_id`,ord.`shipping_fee`,ogd.`supplierid`,ogd.`goods_id`,ogd.`rec_id`,ogd.`goods_name`,ogd.`goods_number`,ogd.`goods_price`,ogd.`purchase_price`,ogd.`goods_type` FROM {$this->_prefix['primary']}order_info ord INNER JOIN {$this->_prefix['primary']}order_goods ogd ON ogd.`order_id` = ord.`order_id` " . $wh . "  ORDER BY ogd.`supplierid` ASC,ogd.`rec_id` ASC";
            $data = $this->sql($sql);
            if($data){
             // dd($data);


                //商品信息
                $goods_ids =  array_unique(array_column($data, 'goods_id'));
                $goods_data = $this->table("goods_data")->findAllBySql("`goods_id` IN (".implode(',',$goods_ids).")","`caid`,`goods_id`,`price_me`,`price_level1`,`commission_setting`,`give_coupon`");
                //$goods_ids_arr = [];
                if($goods_data){
                    foreach($goods_data as $key=> $g){
                        $g['fugou_level3'] = $g['fugou_level2']= 0;//fugou_level3 销售级差西海代理   fugou_level2销售级差良品e店
                        $josn = [];

                        if($g['commission_setting']){

                                $josn= json_decode($g['commission_setting'],true);


                            $g['fugou_level3'] = $josn['fugou']['jicha'][3] ?:0;
                            $g['fugou_level2'] = $josn['fugou']['jicha'][2]?:0;
                        }
                        unset($g['commission_setting']);

                         $goods[$g['goods_id']] = $g;
                    }
                }


                //分类信息
                $caids =  array_unique(array_column($goods, 'caid'));
                $cate = $this->table("goods_category")->findAllBySql("`caid` IN (".implode(',',$caids).")","`caid`,`name`,`fucaid`");
                if($cate){
                    foreach($cate as $kc=>$c){

                        if($c['fucaid']){

                            $fc = $this->table("goods_category")->findBySql("`caid` = ".$c['fucaid'],"`caid`,`name`");
                            $c['fname'] = $fc['name'];
                            $c['rname'] =$c['name'];

                        }else{
                            $c['fname'] = $c['name'];
                            $c['rname'] ="";
                        }

                        $cates[$c['caid']] = $c;

                    }


                }

               // print_r($cates);die;
                $supplier_ids = [];
                $coupon_total_fee = 0;

                foreach($data as $k=>$v){
                     if($v['coupon_fee']){
                         $coupon_total_fee +=$v['coupon_fee'];

                     }

                    $supplier_ids[$v['supplierid']] = $v['supplierid'];
  /*                  $goods = $this->table("goods_data")->findBySql("`goods_id` = ".$v['goods_id'],"`caid`,`goods_name`,`goods_type`");
                     if($goods['caid']){
                         $cate = $this->table("goods_category")->findBySql("`caid` = ".$goods['caid'],"`caid`,`name`,`fucaid`");
                         if($cate['fucaid']){

                             $fcate = $this->table("goods_category")->findBySql("`caid` = ".$cate['fucaid'],"`caid`,`name`,`fucaid`");
                         }else{
                             $fcate['name'] = $cate['name'];
                             $cate['name'] = "";
                         }
                         $v['cate_name1'] = $fcate['name'];
                         $v['cate_name2'] = $cate['name'];

                     }*/

                    $v['cate_name1'] = $cates[$goods[$v['goods_id']]['caid']]['fname'];
                    $v['cate_name2'] = $cates[$goods[$v['goods_id']]['caid']]['rname'];
                   // $cmoney = $this->table("finance_detail")->findOneBySql("`dataid` = ".$v['rec_id']." AND `event` = 8","`cmoney`");
                    $v['fugou_level3'] = $goods[$v['goods_id']]['fugou_level3'];
                    $v['fugou_level2'] = $goods[$v['goods_id']]['fugou_level2'];
                    $v['price_me'] = $goods[$v['goods_id']]['price_me'];
                    $v['price_level1'] = $goods[$v['goods_id']]['price_level1'];
                    $v['give_coupon'] = $goods[$v['goods_id']]['give_coupon'];
                    $v['sale_money'] = fun_price( ($v['goods_price'] - $v['give_coupon']) *$v['goods_number']);
                    $v['goods_type'] = $this->c['goods_type'][$v['goods_type']];
                  //  $v['money'] = $cmoney ?:0;
                    $v['gross_profit'] = fun_price($v['sale_money'] - $v['purchase_price'] - $v['fugou_level3']  );

                    $v['profit_rate'] = fun_price($v['gross_profit'] / $v['sale_money']);

                     if($arr){
                         $done = false;
                         foreach($arr as $ks => $vs){
                             if($vs['supplierid'] ==$v['supplierid'] && $vs['goods_id'] ==$v['goods_id']){
                                 $done = true;
                                  $arr[$ks]['goods_number'] += $v['goods_number'];
                                  $arr[$ks]['money'] += $v['money'];
                                  $arr[$ks]['sale_money'] += $v['sale_money'];
                                  $arr[$ks]['gross_profit'] += $v['gross_profit'];
                                  $arr[$ks]['profit_rate'] = fun_price($arr[$ks]['gross_profit']  / $arr[$ks]['sale_money']);

                             }

                         }
                         if(!$done){

                             $arr[]  = $v;

                         }

                     }else{
                         $arr[]  = $v;

                     }
                }

            }

        }
        //dd($arr);
        $goods_ids =  array_column($arr, 'goods_id');
        return array("data"=>$arr,"supplier_num"=>count($supplier_ids),"goods_num"=>count($goods_ids),"coupon_total_fee"=>$coupon_total_fee);
    }

    //动态表
    public function getDynamicList($para)
    {
        $where = " 1=1 ";//" statu = 1 ";
        $wh = "  ";
        if ($para['keyword'] != '') {
            if(is_numeric($para['keyword'])){
                $where .= "   AND  `id` = ".$para['keyword'];
            }else{
                $where .= "   AND `supplier` LIKE '%" . $para['keyword'] . "%'";
            }

        }



        if ($para['caid'] > 0) {

            $cate = $this->table("goods_category")->findBySql("`caid` = ".$para['caid'],"`caid`,`name`,`fucaid`");
            if($cate['fucaid']>0){

                $c_ids = $cate['fucaid'];
            }else{

                $cates = $this->table("goods_category")->findAllBySql("`fucaid` = ".$cate['caid'],"`caid`,`name`,`fucaid`");

                if($cates){

                    $caids  = array_column($cates, 'caid');
                    $c_ids = implode(",",$caids);
                }
            }

            $goods = $this->table("goods_data")->findAllBySql("`caid`  IN(".$c_ids.")","`goods_id`");
            if($goods){

                $goods_ids  = array_column($goods, 'goods_id');
                if ($para['goods_id'] != '') {
                      if(!in_array($para['goods_id'],$goods_ids)){

                          $goods_ids = array_push($goods_ids,$para['goods_id']);
                      }
                }
            }

            if($goods_ids){
                $wh .= " AND ogd.`goods_id` IN (".implode(',',$goods_ids).")";

            }

        }else{
            if ($para['goods_id'] != '') {
                $wh .= "   AND ogd.`goods_id` = ".$para['goods_id'];
            }

        }

        $arr = [];
        $total_price = 0;
        $total_num = 0;
        $suppliers = $this->table("supplier")->findAllBySql($where,"id,supplier");
        $supp_ids =  array_column($suppliers, 'id');

        if($supp_ids){

            $wh .=" AND ogd.`supplierid` IN (".implode(',',$supp_ids).") AND ord.pay_status>0";
            $sql = "SELECT ord.`uid`,ord.`coupon_fee`,ord.`ximi_fee`,ord.`order_id`,ord.`shipping_fee`,ogd.`supplierid`,ogd.`goods_id`,ogd.`rec_id`,ogd.`goods_name`,ogd.`goods_number`,ogd.`goods_price`,ogd.`purchase_price`,ogd.`goods_type` FROM {$this->_prefix['primary']}order_info ord INNER JOIN {$this->_prefix['primary']}order_goods ogd ON ogd.`order_id` = ord.`order_id` " . $wh . "  ORDER BY ogd.`supplierid` ASC,ogd.`rec_id` ASC";
            $data = $this->sql($sql);
            if($data){
                // dd($data);
                //商品信息
                $goods_idss =  array_unique(array_column($data, 'goods_id'));
                $goods_data = $this->table("goods_data")->findAllBySql("`goods_id` IN (".implode(',',$goods_idss).")","`caid`,`goods_id`,`price_me`,`price_level1`,`commission_setting`,`give_coupon`");
                //$goods_ids_arr = [];
                if($goods_data){
                    foreach($goods_data as $key=> $g){
                        $g['fugou_level3'] = 0;//fugou_level3 销售级差西海代理   fugou_level2销售级差良品e店
                        $josn = [];

                        if($g['commission_setting']){

                            $josn= json_decode($g['commission_setting'],true);


                            $g['fugou_level3'] = $josn['fugou']['jicha'][3] ?:0;
                        }
                        unset($g['commission_setting']);

                        $goods[$g['goods_id']] = $g;
                    }
                }

                $coupon_total_fee = 0;

                foreach($data as $k=>$v){
                    if($v['coupon_fee']){
                        $coupon_total_fee +=$v['coupon_fee'];

                    }
                    $v['sale_money'] = fun_price( ($v['goods_price'] - $goods[$v['goods_id']]['give_coupon']) *$v['goods_number']);
                    $v['gross_profit'] = fun_price($v['sale_money'] - $v['purchase_price'] - $goods[$v['goods_id']]['fugou_level3']  );
                    $v['average_price']  = fun_price($v['goods_price'] / $v['goods_number']);
                    $v['profit_rate'] = fun_price($v['gross_profit'] / $v['sale_money']);

                    if($arr){
                        $done = false;
                        foreach($arr as $ks => $vs){



                            if($vs['supplierid'] ==$v['supplierid'] && $vs['goods_id'] ==$v['goods_id']){
                                $done = true;
                                $arr[$ks]['goods_number'] += $v['goods_number'];
                                $arr[$ks]['money'] += $v['money'];
                                $arr[$ks]['sale_money'] += $v['sale_money'];
                                $arr[$ks]['gross_profit'] += $v['gross_profit'];
                                $arr[$ks]['profit_rate'] = fun_price($arr[$ks]['gross_profit']  / $arr[$ks]['sale_money']);
                                $arr[$ks]['average_price'] = fun_price($arr[$ks]['sale_money'] / $arr[$ks]['goods_number']);
                            }

                        }

                        if(!$done){

                            $arr[]  = $v;

                        }

                    }else{
                        $arr[]  = $v;

                    }

                }


            }

            if($arr){
                $sort_names = array_column($arr,'sale_money');
                //dd($sort_names);die;
                array_multisort($sort_names,SORT_DESC,$arr);

                foreach($arr as $r){
                    $total_price +=$r['sale_money'];
                    $total_num +=$r['goods_number'];
                }


            }

        }

        $price = fun_price($total_price / $total_num);

        return array("data"=>$arr,"price"=>$price,"coupon_total_fee"=>$coupon_total_fee,"para"=>$para);

    }
    // 获取热销商品
    public function getBestsell($para)
    {

        if ($para['caid'] > 0 || $para['start_time'] > 0 || $para['end_time'] > 0) {
            if ($para['caid'] > 0 && $para['start_time'] == 0 && $para['start_time'] == 0) {
                $caids = $this->getSmlCate($para['caid']);
                if ($caids) {
                    $caids[] = $para['caid'];
                    $tsql    = "gd.`caid` IN (" . implode(",", $caids) . ")";
                } else {
                    $tsql = "gd.`caid`=" . $para['caid'];
                }

                $sql = "SELECT SUM(og.`goods_number`) AS `cnt`,og.`goods_id`,og.`goods_name`,og.`goods_sn`,og.`goods_price` FROM {$this->_prefix['primary']}order_goods og INNER JOIN {$this->_prefix['primary']}goods_data gd ON og.`goods_id` = gd.`goods_id` AND " . $tsql . " GROUP BY og.`goods_id` ORDER BY `cnt` DESC";
            } elseif ($para['caid'] == 0 && ($para['start_time'] > 0 || $para['end_time'] > 0)) {
                if ($para['start_time'] > 0) {
                    $tsql .= " AND `add_time`>=" . $para['start_time'];
                }

                if ($para['end_time'] > 0) {
                    $tsql .= " AND `add_time`<=" . $para['end_time'];
                }

                $sql = "SELECT SUM(`goods_number`) AS `cnt`,`goods_id`,`goods_name`,`goods_sn`,`goods_price` FROM {$this->_prefix['primary']}order_goods WHERE 1 " . $tsql . " GROUP BY `goods_id` ORDER BY `cnt` DESC";

            } elseif ($para['caid'] > 0 && ($para['start_time'] > 0 || $para['end_time'] > 0)) {
                $caids = $this->getSmlCate($para['caid']);
                if ($caids) {
                    $caids[] = $para['caid'];
                }

                if ($para['start_time'] > 0) {
                    $tsql .= " AND og.`add_time`>=" . $para['start_time'];
                }

                if ($para['end_time'] > 0) {
                    $tsql .= " AND og.`add_time`<=" . $para['end_time'];
                }

                $sql = "SELECT SUM(og.`goods_number`) AS `cnt`,og.`goods_id`,og.`goods_name`,og.`goods_sn`,og.`goods_price` FROM {$this->_prefix['primary']}order_goods og INNER JOIN {$this->_prefix['primary']}goods_data gd ON og.`goods_id` = gd.`goods_id` AND gd.`caid` IN (" . implode(",", $caids) . ") " . $tsql . " GROUP BY og.`goods_id` ORDER BY `cnt` DESC";

            }
        } else {
            $sql = "SELECT SUM( `goods_number` ) AS `cnt`, `goods_id`,`goods_name`,`goods_sn`,`goods_price` FROM {$this->_prefix['primary']}order_goods GROUP BY `goods_id` ORDER BY `cnt` DESC";
        }

        $data = $this->sql($sql);

        return array('data' => $data, 'para' => $para);
    }

}
